//index.js
//获取应用实例
const app = getApp();

Page({
  data:{
    /* 用户信息 */
    userInfo_share:app.globalData.userInfo_share,
    /* 导航栏参数 */
    navH: 0,
    navPT: 0,
    navOV: 0,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    /* 内容区显示隐藏 */
    toggleContentArea: false,
    //与客户对应的企业员工名片数据
    pickerData: [],
    pickerTitle: '', //显示的员工姓名
    pickerValue: '', //所选择的员工
    /*  */
    hide_drawimage: true,
    /*  */
    showCanvasPop: true, //显示隐藏canvas弹层
    /* canvas生成的图片链接 */
    ctx: null,
    ox: 0, //画布绘制时相对屏幕宽的左侧偏移
    initY: 38, //
    canvasImgSrc: '', //canvas生成的图片链接
    //
    employeeInfo: {
      visit_avatars_arr: [] //已浏览的用户头像
    }, //员工信息
    corp_userid: '', //从分享页进来的时候???--名片人的企业userid
    share_userid:'', //从分享页进来的时候???--分享名片的用户userid
    position: '', //职位--分享用
    name: '', //姓名--分享用
    source: '', //添加名片访问记录--来源：0、系统随机派发，1、名片分享
    hasScene: false, //从分享页进来
    //图片分类信息
    sysImgsInfo: [],
    //添加微信弹层
    showAddWechatPop: true,
    /* 推广数据 */
    extendsData: []
  },
  /* 登录后->产品分享和小程序二维码识别 */
  loginedToOtherPage(){
    //从产品分享跳转--已登录
    if(wx.getStorageSync('product-share-notlogin')){
      app.globalData.indexloginedToPSN = true;
      //跳转到产品详情页
      wx.navigateTo({
        url: '/pages/shoppingMallMini/shoppingMallMini',
      })
    }
    //从二维码识别产品跳转---已登录
    if(wx.getStorageSync('miniqrcode_distinguish_notlogin')){
      app.globalData.indexloginedToMDN = true;
      //跳转到产品详情页
      wx.navigateTo({
        url: '/pages/shoppingMallMini/shoppingMallMini',
      })
    }
  },
  /*  */
  startmessageMultiplecell:function(){
    wx.showLoading({
      title: '',
      mask:true
    })
  },
  /*  */
  completemessageMultiplecell:function(e){
    wx.hideLoading();
    if(e.detail.errcode=='0'){
      wx.showModal({
        title:'提示',
        content:`${this.data.name}邀请您加入群聊的微信消息已发送`,
        showCancel:false
      });
    }
  },
  /*  */
  startmessage: function (e) {
    //console.log('startmessage-----------singlecell');
    //console.log(e);
    wx.showLoading({
      title: '',
      mask:true
    })
  },
  /*  */
  completemessage: function (e) {
    console.log('completemessage-----------singlecell');
    console.log(e);
    wx.hideLoading();
    if(e.detail.errcode=='0'){
      wx.showModal({
        title:'提示',
        content:`${this.data.name}邀请您添加好友的微信消息已发送`,
        showCancel:false
      });
    }
  },
  /* 配置客户联系「联系我」方式 */
  getCorpUserConfigId: function () {
    return app.globalData.getCorpUserConfigId.call(this,app.globalData.visit_userid).then(config_id=>{
      this.setData({
        'userInfo_share.singlePlugid': config_id
      });
      //信息存缓存
      wx.setStorageSync('userInfo_share', this.data.userInfo_share);
    }).catch(err=>{
      return Promise.reject(`${err}`)
    })
  },
  /* 根据用户角色点击个人中心跳转到对应的界面 */
  goToPersonalPage: function () {
    if (!this.data.userInfo_share.mobile) {
      return;
    }
    //客户
    if (this.data.userInfo_share.state === '0') {
      wx.navigateTo({
        url: '/pages/personal/personal',
      })
    }
    //企业员工
    if (this.data.userInfo_share.state === '1') {
      wx.navigateTo({
        url: '/pages/employee/employee',
      })
    }
  },
  /* 获取推广和图片分类数据 */
  getExtendsImgData: function () {
    return Promise.all([
      this.getExtends()
    ]);
  },
  /* 获取用户手机号码 + 用户登录 */
  getPhoneNumber: function (e) {
    //console.log(e);
    return app.globalData.getPhoneNumber.call(this,e);
  },
  /* 获取用户信息 */
  getUserInfoFn: function (e) {
    //console.log(e);
    app.globalData.getUserInfoFn.call(this,e);
  },
  /* 刚进入页面时 */
  pageInit: function () {
    wx.showLoading({
      title: '',
      mask: true
    });
    return app.globalData.wx_login.call(this).then(data => {
      return app.globalData.user_getSissonkey.call(this,data);
    }).then(() => {
      //
      wx.hideLoading();
      //显示内容区域
      this.setData({
        toggleContentArea: false
      });
      //
    }).catch(err => {
      //
      wx.hideLoading();
      //
      wx.showModal({
        title: '提示',
        content: '' + err,
        showCancel: false,
        success: res => {
          if (res.confirm) {
            /* wx.reLaunch({
              url:'/pages/index/index'
            }); */
          }
        }
      });
    });
  },
  /* 分享小程序名片 */
  onShareAppMessage: function () {
    //console.log("this.data.userInfo_share.userid");
    //console.log(this.data.userInfo_share.userid);
    //
    if (this.data.corp_userid) {
      return {
        title: `你好，我是${app.globalData.sysName}的${this.data.position}${this.data.name}^_^`,
        //path: 'pages/index/index?scene=' + this.data.corp_userid, //点击分享消息时打开的页面
        path:`pages/index/index?scene=${this.data.corp_userid}_${this.data.userInfo_share.userid}`
      };
    }
    //

    /* return {
      title: '分享给好友',
      path: 'pages/index/index?scene=' + that.data.openid,//点击分享消息是打开的页面
      imageUrl: that.data.saveImgSrc,
      success: function (res) {
        // 转发成功
        console.log("转发成功:" + JSON.stringify(res));
        var shareTickets = res.shareTickets;
      },
      fail: function (res) {
        // 转发失败
        console.log("转发失败:" + JSON.stringify(res));
      }
    } */
  },
  /*  */
  onHide:function(){
    
  },
  /*  */
  onShow: function () {
    /* 
      (从产品页登录之后再返回首页）
      (从对应的产品页登录之后再返回首页）  
    */
    if (app.globalData.loginedFromOtherPage&&!this.data.userInfo_share.mobile) {
      //
      app.globalData.loginedFromOtherPage = false;
      wx.reLaunch({
        url: '/pages/index/index',
      });
    }
    //---20200714
    //(this.data.userInfo_share.mobile) && (app.globalData.user_loginWx.call(this))
  },
  onReady: function () {
    //获取canvas
    /* new Promise((resolve, reject) => {
      const query = wx.createSelectorQuery()
      query.select('#index-canvas')
        .fields({ node: true, size: true })
        .exec((res) => {
          console.log(res);
          const canvas = res[0].node;
          const ctx = canvas.getContext('2d');
          const dpr = wx.getSystemInfoSync().pixelRatio;
          canvas.width = res[0].width * dpr;
          canvas.height = res[0].height * dpr;
          ctx.scale(dpr, dpr);
          //
          this.setData({
            canvas: canvas
          });
          resolve()
        })
    }).then(()=>{
        console.log(this.data.canvas.width);
    }); */
    //获取canvas-context
    //console.log(app.globalData.windowWidth);
    //console.log(app.globalData.windowHeight);
    /* const ctx = wx.createCanvasContext('index-canvas', this);
    this.setData({
      ctx: ctx,
      ox: 0
    }); */
    app.globalData.getCanvas.call(this,'index-canvas')
  },
  onLoad: function (options) {
    //console.log(app.globalData.dataTypes);
    //获取用户信息
    this.setData({
      userInfo_share: app.globalData.get_userInfo()
    });
    //console.log(this.data.userInfo_share);
    //获取设备信息
    app.globalData.getSystemInfo().then(data => {
      //设置自定义导航的高度
      this.setData({
        navH: data.hv,
        navPT: data.pt,
        navOV: data.ov
      });
      //
      //小程序版本更新
      try {
        if(wx.canIUse('getUpdateManager')){
          const updateManager = wx.getUpdateManager();
          updateManager.onCheckForUpdate(res=>{
            console.log(res);
            //是否有新版本
            if(res.hasUpdate){
              // 新版本下载成功时执行
              updateManager.onUpdateReady(()=>{
                wx.showModal({
                  title: '更新提示',
                  content: '新版本已经准备好，是否重启当前应用？',
                  showCancel:false,
                  success(res) {
                    if (res.confirm) {
                      // 新的版本已经下载好，调用applyUpdate应用新版本并重启
                      updateManager.applyUpdate()
                    }
                  }
                });
              });
              // 新版本下载失败时执行
              updateManager.onUpdateFailed(()=>{
                wx.showModal({
                  title: '发现新版本',
                  content: `请删除当前小程序，重新搜索“${app.globalData.sysName}”打开...`,
                })
              });
            }
          });
        }else{
          //如果小程序需要在最新的微信版本体验，如下提示
          wx.showModal({
            title:'提示',
            content:'当前微信版本过低，无法使用版本更新功能，请升级到最新微信版本后重试版本更新。'
          });
        }  
      } catch (error) {
        console.log(error);
      }
      //从分享页进来
      let scene = decodeURIComponent(options.scene);
      console.log(scene);
      //console.log(typeof scene);
      if (typeof scene === 'string' && scene !== 'undefined') {
        let sceneArr = scene.split("_")
        this.setData({
          hasScene: true,
          corp_userid: sceneArr[0],
          share_userid:sceneArr[1]
        });
        //分享的标记
        wx.setStorageSync('scene', sceneArr[0]);
        wx.setStorageSync('share_userid', sceneArr[1]);
        wx.setStorageSync('source', '1');
      }
      //从产品分享跳转--未登录
      if(app.globalData.product_share_notlogin){
        app.globalData.product_share_notlogin = false;
        //
        let tmpObj = wx.getStorageSync('product-share-notlogin');
        //
        this.setData({
          corp_userid:tmpObj.scene
        });
      }
      //从二维码识别产品跳转---未登录
      if(app.globalData.miniqrcode_distinguish_notlogin){
        app.globalData.miniqrcode_distinguish_notlogin = false;
        //
        let tmpObj = wx.getStorageSync('miniqrcode_distinguish_notlogin');
        //
        this.setData({
          corp_userid:tmpObj.scene
        });
      }
      //页面初始化---用户未授权获取信息和手机号码，未登录
      if (!this.data.userInfo_share.mobile && !this.data.userInfo_share.userid) {
        //未登录
        wx.setStorageSync('notLogin', true);
        //
        this.pageInit().then(() => {
          //获取推广和图片分类数据
          return this.getExtendsImgData();
        }).then(() => {
          return this.getCorpUser();
        }).then(() => {
          //存默认员工的名片userid---(登录成功 + 客户)用
          wx.setStorageSync('first_open_corp_userid', this.data.employeeInfo.userid);
          wx.setStorageSync('first_open_corp_userName', this.data.employeeInfo.name);
          wx.setStorageSync('first_open_corp_position', this.data.employeeInfo.position);
          //
          app.globalData.visit_userid = this.data.employeeInfo.userid;
          //分享用 + 默认分享的职位和姓名
          this.setData({
            corp_userid: this.data.employeeInfo.userid,
            share_userid: wx.getStorageSync('share_userid'),
            position: this.data.employeeInfo.position,
            name: this.data.employeeInfo.name
          });
          //默认销售电话 
          app.globalData.init_sale_name = this.data.employeeInfo.name;
          app.globalData.init_sale_phone = this.data.employeeInfo.mobile;
          //默认销售的微信
          app.globalData.init_sale_wechat = this.data.employeeInfo.qr_code;
        }).catch(err => {
          console.log(err);
          wx.showModal({
            title: '提示',
            content: '' + err,
            showCancel: false
          });
        });
      } else {
        //已登录
        this.setData({
          toggleContentArea: false
        });
        //
        wx.showLoading({
          title: '',
          mask: true
        });
        //客户
        if (this.data.userInfo_share.state === '0') {
          //从分享进入且(未登录->已登录)
          if (wx.getStorageSync('source') && wx.getStorageSync('notLogin')) {
            //
            this.setData({
              corp_userid: wx.getStorageSync('scene'), //名片分享的企业员工
              share_userid: wx.getStorageSync('share_userid'), //分享者的userid
              source: wx.getStorageSync('source') //名片分享
            });
            //
            this.getExtendsImgData().then(() => {
              //添加已浏览的员工信息
              return this.insertVisitLog();
            }).then(() => {
              //获取用户浏览过的销售员名片数据
              return this.getWxUserCorpUser();
            }).then(() => {
              //设置切换员工下拉的默认显示
              this.data.pickerData.forEach((item, i) => {
                if (item.visit_userid === this.data.corp_userid) {
                  this.setData({
                    corp_userid: item.visit_userid,
                    pickerTitle: item.visit_name,
                    pickerValue: '' + i
                  });
                }
              });
              //显示首页名片信息
              return this.getCorpUser();
            }).then(() => {
              //分享用 + 默认分享的职位和姓名
              this.setData({
                corp_userid: this.data.employeeInfo.userid,
                position: this.data.employeeInfo.position,
                name: this.data.employeeInfo.name
              });
              //生成订单的时候用
              app.globalData.visit_userid = this.data.employeeInfo.userid;
              //默认销售电话
              app.globalData.init_sale_name = this.data.employeeInfo.name; 
              app.globalData.init_sale_phone = this.data.employeeInfo.mobile;
              //默认销售的微信
              app.globalData.init_sale_wechat = this.data.employeeInfo.qr_code;
              return this.visitUser();
            }).then(()=>{
              return this.getCorpUserConfigId();
            }).then(() => {
              wx.hideLoading();
              //清除标记
              wx.removeStorageSync('scene');
              wx.removeStorageSync('share_userid');
              wx.removeStorageSync('source');
              wx.removeStorageSync('notLogin');
              //
              this.loginedToOtherPage();
            }).catch(err => {
              wx.hideLoading();
              wx.showModal({
                title: '提示',
                content: '' + err,
                showCancel: false
              })
            });
            return;
          }
          //从分享进入(已登录)
          if (wx.getStorageSync('source')) {
            //
            this.setData({
              corp_userid: wx.getStorageSync('scene'), //名片分享的企业员工
              share_userid: wx.getStorageSync('share_userid'), //分享者的userid
              source: wx.getStorageSync('source') //名片分享
            });
            //
            let tmpArr = this.data.pickerData.filter(item => item.visit_userid === wx.getStorageSync('scene'));
            //
            this.getExtendsImgData().then(() => {
              //添加已浏览的员工信息
              return tmpArr.length ? Promise.resolve() : this.insertVisitLog();
            }).then(() => {
              //获取用户浏览过的销售员名片数据
              return tmpArr.length ? Promise.resolve() : this.getWxUserCorpUser();
            }).then(() => {
              //设置切换员工下拉的默认显示
              this.data.pickerData.forEach((item, i) => {
                if (item.visit_userid === this.data.corp_userid) {
                  this.setData({
                    corp_userid: item.visit_userid,
                    pickerTitle: item.visit_name,
                    pickerValue: '' + i
                  });
                }
              });
              //显示首页名片信息
              return this.getCorpUser();
            }).then(() => {
              //分享用 + 默认分享的职位和姓名
              this.setData({
                corp_userid: this.data.employeeInfo.userid,
                position: this.data.employeeInfo.position,
                name: this.data.employeeInfo.name
              });
              //生成订单的时候用
              app.globalData.visit_userid = this.data.employeeInfo.userid;
              //默认销售电话 
              app.globalData.init_sale_name = this.data.employeeInfo.name;
              app.globalData.init_sale_phone = this.data.employeeInfo.mobile;
              //默认销售的微信
              app.globalData.init_sale_wechat = this.data.employeeInfo.qr_code;
              return this.visitUser();
            }).then(()=>{
              return this.getCorpUserConfigId();
            }).then(() => {
              wx.hideLoading();
              //清除标记
              wx.removeStorageSync('scene');
              wx.removeStorageSync('share_userid');
              wx.removeStorageSync('source');
              //
              this.loginedToOtherPage();
            }).catch(err => {
              wx.hideLoading();
              wx.showModal({
                title: '提示',
                content: '' + err,
                showCancel: false
              })
            });
            return;
          }
          //不从分享页进入页面
          if (!wx.getStorageSync('source')) {
            //
            this.setData({
              corp_userid: wx.getStorageSync('first_open_corp_userid'), //企业员工
              source: '0' //随机分配
            });
            //
            this.getExtendsImgData().then(() => {
              //添加已浏览的员工信息
              return this.insertVisitLog();
            }).then(() => {
              //获取用户浏览过的销售员名片数据
              return this.getWxUserCorpUser();
            }).then(() => {
              //设置切换员工下拉的默认显示
              this.data.pickerData.forEach((item, i) => {
                if (item.visit_userid === this.data.corp_userid) {
                  this.setData({
                    corp_userid: item.visit_userid,
                    pickerTitle: item.visit_name,
                    pickerValue: '' + i
                  });
                }
              });
              //显示首页名片信息
              return this.getCorpUser();
            }).then(() => {
              //
              wx.setStorageSync('first_open_corp_userid', this.data.employeeInfo.userid);
              //分享用 + 默认分享的职位和姓名
              this.setData({
                corp_userid: this.data.employeeInfo.userid,
                position: this.data.employeeInfo.position,
                name: this.data.employeeInfo.name
              });
              //生成订单的时候用
              app.globalData.visit_userid = this.data.employeeInfo.userid;
              //默认销售电话 
              app.globalData.init_sale_name = this.data.employeeInfo.name; 
              app.globalData.init_sale_phone = this.data.employeeInfo.mobile;
              //默认销售的微信
              app.globalData.init_sale_wechat = this.data.employeeInfo.qr_code;
              return this.visitUser();
            }).then(()=>{
              return this.getCorpUserConfigId();
            }).then(() => {
              wx.hideLoading();
              //
              this.loginedToOtherPage();
            }).catch(err => {
              wx.hideLoading();
              wx.showModal({
                title: '提示',
                content: '' + err,
                showCancel: false
              })
            });
          }
        }
        //企业员工
        if (this.data.userInfo_share.state === '1') {
          //存管理者标识
          app.globalData.is_manager = this.data.userInfo_share.corpUser.is_manage
          app.globalData.visit_userid = this.data.userInfo_share.corpUser.userid;
          //查看自己的名片
          this.setData({
            corp_userid: this.data.userInfo_share.corpUser.userid,
            position: this.data.userInfo_share.corpUser.position,
            name: this.data.userInfo_share.corpUser.name
          });
          this.getExtendsImgData().then(() => {
            return this.getCorpUser()
          }).then(()=>{
            return this.getCorpUserConfigId();
          }).then(() => {
            wx.hideLoading();
            //
            this.loginedToOtherPage();
          }).catch(err => {
            wx.hideLoading();
            wx.showModal({
              title: '提示',
              content: '' + err,
              showCancel: false
            });
          });
        }
      }
    });
  },
  /* 切换员工--非企业员工用 */
  changeCorpUser: function (e) {
    console.log(e.detail.value);
    console.log(this.data.pickerData[e.detail.value * 1]);
    if (e.detail.value == this.data.pickerValue) {
      return;
    }
    //
    if(this.data.share_userid){
      this.setData({
        share_userid:''
      })
    }
    //关闭名片弹层
    this.setData({
      showCanvasPop: true
    });
    //
    wx.setStorageSync('first_open_corp_userid', this.data.pickerData[e.detail.value * 1].visit_userid);
    //
    this.setData({
      corp_userid: this.data.pickerData[e.detail.value * 1].visit_userid,
      pickerTitle: this.data.pickerData[e.detail.value * 1].visit_name,
      pickerValue: e.detail.value
    });
    //生成订单的时候用
    app.globalData.visit_userid = this.data.pickerData[e.detail.value * 1].visit_userid;
    //
    wx.showLoading({
      title: '切换员工信息',
      mask: true
    });
    //
    this.getCorpUser().then(() => {
      //分享用
      this.setData({
        position: this.data.employeeInfo.position,
        name: this.data.employeeInfo.name
      });
      //默认销售电话
      app.globalData.init_sale_name = this.data.employeeInfo.name; 
      app.globalData.init_sale_phone = this.data.employeeInfo.mobile;
      //默认销售的微信
      app.globalData.init_sale_wechat = this.data.employeeInfo.qr_code;
      return this.visitUser();
    }).then(()=>{
      return this.getCorpUserConfigId();
    }).then(() => {
      wx.hideLoading();
    }).catch(err => {
      wx.hideLoading();
    });
  },
  /* 添加名片访问记录 */
  insertVisitLog: function () {
    return app.globalData.$http.call(this,{
      api:"/insertVisitLog",
      data:{
        source: this.data.source, //来源：0、系统随机派发，1、名片分享
        userid: this.data.userInfo_share.userid, //访问者id
        visit_userid: this.data.corp_userid //被访问者id
      }
    }).then(res=>{
      return Promise.resolve()
    }).catch(err=>{
      return Promise.reject('添加浏览员工访问记录失败');
    })
  },
  /* 获取用户对应销售员名片列表--客户用 */
  getWxUserCorpUser: function () {
    return app.globalData.$http.call(this,{
      api:"/getWxUserCorpUser",
      data:{
        userid: this.data.userInfo_share.userid
      }
    }).then(res=>{
      if (res.data.code == '1') {
        this.setData({
          //pickerData:res.data.body.filter(item=>item.visit_userid&&item.visit_name)
          pickerData: res.data.body
        })
        return Promise.resolve()
      } else {
        return Promise.reject('获取用户对应销售员名片失败');
      }
    }).catch(err=>{
      return Promise.reject('获取用户对应销售员名片失败');
    })
  },
  /* 浏览员工个人信息 */
  visitUser: function () {
    return app.globalData.visitUser.call(this,{
      userid: this.data.userInfo_share.userid, //
      visit_userid: this.data.corp_userid,  //
      share_userid: this.data.share_userid  //
    })
  },
  /* 获取推广数据 */
  getExtends: function () {
    return app.globalData.$http.call(this,{
      api:"/getExtends",
      data:{}
    }).then(res=>{
      //console.log(res);
      if (res.data.code == '1') {
        //
        let tmpData = [];
        res.data.body.forEach(item => {
          let desc = item.descibe?JSON.parse(item.descibe):"";
          item.desc = desc
        });
        //
        this.setData({
          extendsData: res.data.body
        });
        //
        return Promise.resolve()
      } else {
        return Promise.reject('获取推广数据失败');
      }
    }).catch(err=>{
      return Promise.reject('获取推广数据失败');
    })
  },
  /* 获取员工个人信息 */
  getCorpUser: function () {
    return app.globalData.$http.call(this,{
      api:"/getCorpUser",
      data:{
        appid:app.globalData.accountInfo.miniProgram.appId,
        corp_userid: this.data.corp_userid, //
        wx_userid: this.data.userInfo_share.userid //当前小程序用户userid
      }
    }).then(res=>{
      console.log(res);
      this.setData({
        employeeInfo: res.data.body,
        'userInfo_share.corp.address':res.data.body.address,
        'userInfo_share.corp.app_name':res.data.body.app_name,
        'userInfo_share.corp.corp_name':res.data.body.corp_name
      });
      //信息存缓存
      wx.setStorageSync('userInfo_share', this.data.userInfo_share)
      //是否有浏览过人员图片数据
      if (this.data.employeeInfo.visit_avatars) {
        this.setData({
          'employeeInfo.visit_avatars_arr': this.data.employeeInfo.visit_avatars.split(',').filter(item => item !== '')
        })
      }
    }).catch(err=>{
      return Promise.reject('获取员工信息失败');
    })
  },
  /* 点赞员工 */
  praiseUser: function () {
    //是否已获取手机号码
    if (!this.data.userInfo_share.mobile) {
      return;
    }
    if (this.data.userInfo_share.corpUser && this.data.userInfo_share.corpUser.userid === this.data.employeeInfo.userid) {
      wx.showToast({
        icon: 'none',
        title: '不能给自己点赞'
      });
      return;
    }
    if (this.data.employeeInfo.ispraise !== '0') {
      wx.showToast({
        icon: 'none',
        title: '已经点过赞啦'
      });
      return;
    }
    wx.showLoading({
      title: '点赞...',
      mask: true
    })
    return app.globalData.$http.call(this,{
      api:"/praiseUser",
      data:{
        praise_userid: this.data.employeeInfo.userid, //被点赞用户id
        userid: this.data.userInfo_share.userid //点赞用户id
      }
    }).then(res=>{
      if (res.data.code == '1') {
        //点赞成功--重新获取员工个人信息
        return this.getCorpUser();
      } else {
        // wx.showToast({
        //   icon:'none',
        //   title:'获取员工信息失败'
        // });
        wx.hideLoading();
      }
    }).then(()=>{
      wx.hideLoading();
    }).catch(err=>{
      wx.hideLoading();
      return Promise.reject('点赞失败');
    })
  },
  //绘制背景图
  paintBg: function () {
    let tmpSrc = '../../assets/images/index-userinfo-bg.png';
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: tmpSrc,
        success: res => {
          //console.log(res);
          //console.log(app.globalData.windowWidth);
          //this.data.ctx.drawImage(`/${res.path}`, 0, 0, 375, 226);  
          this.data.ctx.drawImage(`/${res.path}`, 0, 0, app.globalData.windowWidth, 221);
          this.data.ctx.draw(true);
          resolve();
        },
        fail: err => {
          console.log(err);
          reject('绘制名片背景图失败');
        }
      });
    });
  },
  //绘制个人信息
  paintUserInfo: function () {
    return new Promise((resolve, reject) => {
      //console.log(app.globalData.windowWidth);
      let topY;
      let name = this.data.employeeInfo.name;
      //姓名
      this.data.ctx.setFontSize(20);
      let namejg = 20 * 1;
      this.data.ctx.fillStyle = '#333';
      this.data.ctx.fillText(name, 25, this.data.initY);
      this.data.ctx.draw(true);
      //
      //console.log(this.data.ctx.measureText(`${name}`));
      //
      topY = this.data.initY + namejg;
      //职位
      let job = this.data.employeeInfo.position;
      this.data.ctx.setFontSize(12);
      let jobjg = 12 * 1.3;
      this.data.ctx.fillStyle = '#333';
      this.data.ctx.fillText(job, 25, topY);
      this.data.ctx.draw(true);
      topY += jobjg;
      //公司名
      let companyName = this.data.userInfo_share.corp.corp_name;
      this.data.ctx.setFontSize(11);
      this.data.ctx.fillStyle = '#62636D';
      let results = this.textByteLength(companyName, app.globalData.windowWidth <= 320 ? 14 : 16);
      //console.log(topY);
      //console.log(results);
      let cnjg = 11 * 1.3;
      for (let i = 0; i < results.length; i++) {
        this.data.ctx.fillText(results[i], 25, topY + (cnjg * i));
      }
      topY += cnjg * results.length;
      this.data.ctx.draw(true);
      //间隔线
      this.data.ctx.moveTo(25, topY);
      this.data.ctx.lineTo(app.globalData.windowWidth <= 320 ? 174 : 194, topY);
      this.data.ctx.setLineWidth(0.5);
      this.data.ctx.strokeStyle = '#E3E3E3';
      this.data.ctx.stroke();
      this.data.ctx.draw(true);
      //手机号码
      let phoneNumber = this.data.employeeInfo.mobile || '-';
      topY += 8;
      //邮箱
      let email = this.data.employeeInfo.email || '-';
      //地址
      let address = this.data.userInfo_share.corp.address;
      Promise.all([
        this.paintPhone(topY, phoneNumber),
        this.paintEmail(topY, email),
        this.paintAddress(topY, address)
      ]).then(resolve).catch(err => {
        reject('绘制个人信息发生错误')
      });
      //
    });
  },
  //手机号码
  paintPhone: function (topY, phone) {
    return new Promise((resolve, reject) => {
      let tmpSrc = '../../assets/images/index-icon-dh.png';
      wx.getImageInfo({
        src: tmpSrc,
        success: res => {
          //console.log(res);
          //console.log(app.globalData.windowWidth);
          this.data.ctx.drawImage(`/${res.path}`, 22, topY, 20, 20);
          this.data.ctx.draw(true);
          //
          this.data.ctx.setFontSize(12);
          let jobjg = 12 * 1.3;
          this.data.ctx.fillStyle = '#333';
          this.data.ctx.fillText(phone, 22 + 26, topY + 14);
          this.data.ctx.draw(true);
          resolve();
        },
        fail: err => {
          console.log(err);
          reject();
        }
      });
    });
  },
  //邮箱
  paintEmail: function (topY, emali) {
    return new Promise((resolve, reject) => {
      let tmpSrc = '../../assets/images/index-icon-yx.png';
      wx.getImageInfo({
        src: tmpSrc,
        success: res => {
          //console.log(res);
          //console.log(app.globalData.windowWidth);
          this.data.ctx.drawImage(`/${res.path}`, 22, topY + 22, 20, 20);
          this.data.ctx.draw(true);
          //
          this.data.ctx.setFontSize(12);
          this.data.ctx.fillStyle = '#333';
          this.data.ctx.fillText(emali, 22 + 26, topY + 22 + 14);
          /* let results = this.textByteLength(emali, 18);
          let emailjg = 12 * 1.3;
          for (let i = 0; i < results.length; i++) {
            this.data.ctx.fillText(results[i], 25 + 26, (topY + 22 + 14) + (emailjg * i));
          }
          topY = (topY + 22 + 14) + (emailjg*results.length); */
          this.data.ctx.draw(true);
          resolve();
        },
        fail: err => {
          console.log(err);
          reject();
        }
      });
    });
  },
  //地址
  paintAddress: function (topY, address) {
    return new Promise((resolve, reject) => {
      let tmpSrc = '../../assets/images/index-icon-wz.png';
      wx.getImageInfo({
        src: tmpSrc,
        success: res => {
          //console.log(res);
          //console.log(app.globalData.windowWidth);
          this.data.ctx.drawImage(`/${res.path}`, 22, topY + 44, 20, 20);
          this.data.ctx.draw(true);
          //
          this.data.ctx.setFontSize(12);
          this.data.ctx.fillStyle = '#333';
          //this.data.ctx.fillText(address, 25+26, topY+44+14);
          let results = this.textByteLength(address, 14);
          let dzjg = 11 * 1.3;
          for (let i = 0; i < results.length; i++) {
            this.data.ctx.fillText(results[i], 22 + 26, (topY + 44 + 14) + (dzjg * i));
          }
          this.data.ctx.draw(true);
          resolve();
        },
        fail: err => {
          console.log(err);
          reject();
        }
      });
    });
  },
  //绘制简介信息
  paintIntro: function (userName, job) {
    console.log(job);
    return new Promise((resolve, reject) => {
      try {
        let topY = 168;
        this.data.ctx.setFontSize(16);
        let jg = 16 * 1.3;
        this.data.ctx.fillStyle = '#333';
        this.data.ctx.fillText('您好！', 24, topY + 66);
        this.data.ctx.draw(true);
        topY += 66 + jg;
        //
        this.data.ctx.setFontSize(16);
        this.data.ctx.fillStyle = '#333';
        let results = this.textByteLength(`我是${this.data.userInfo_share.corp.app_name}${job}${userName}`, 22);
        //console.log(results);
        //console.log(results.length);
        for (let i = 0; i < results.length; i++) {
          this.data.ctx.fillText(results[i], 24, topY + (jg * i));
          this.data.ctx.draw(true);
        }
        topY += jg * results.length;
        this.data.ctx.setFontSize(16);
        this.data.ctx.fillStyle = '#333';
        this.data.ctx.fillText(`这是我的名片，请惠存 谢谢。`, 24, topY);
        this.data.ctx.draw(true);
        //间隔线
        this.data.ctx.moveTo(26, topY + 90);
        this.data.ctx.lineTo(56, topY + 90);
        this.data.ctx.setLineWidth(3);
        this.data.ctx.strokeStyle = '#2D8CF0';
        this.data.ctx.stroke();
        this.data.ctx.draw(true);
        //
        this.data.ctx.setFontSize(12);
        this.data.ctx.fillStyle = '#333';
        this.data.ctx.fillText(`长按识别二维码 添加微信`, 24, topY + 112);
        this.data.ctx.draw(true);

        resolve(topY);
      } catch (error) {
        reject('绘制简介信息发生错误')
      }

    });
  },
  //绘制二维码
  paintQrCode: function (topY) {
    return new Promise((resolve, reject) => {
      let tmpSrc = this.data.employeeInfo.qr_code || '../../assets/images/homePage-banner2.png';
      // wx.getImageInfo({
      //   src: tmpSrc,
      //   success: res => {
      //     console.log(res);
      //     this.data.ctx.drawImage(`${res.path}`, 243, topY + 40, 76, 76);
      //     this.data.ctx.draw(true);
      //     resolve();
      //   },
      //   fail: err => {
      //     console.log(err);

      //     reject(err);
      //   }
      // });
      wx.downloadFile({
        url: tmpSrc,
        success: res => {
          /* 243 */
          this.data.ctx.drawImage(`${res.tempFilePath}`, (app.globalData.windowWidth - 76 - 76 / 2), topY + 40, 76, 76);
          this.data.ctx.draw(true);
          resolve();
        },
        fail: err => {
          reject('绘制二维码失败')
        }
      })
    });
  },
  //文字需要多行显示时
  textByteLength: function (text, num) { // text为传入的文本  num为单行显示的字节长度
    let textArr = text.split('');
    let count = Math.ceil(textArr.length / num);
    let result = [];
    for (let i = 0; i < count; i++) {
      let tmpArr = [];
      for (var j = 0; j < num; j++) {
        if (!textArr.length) {
          break;
        }
        tmpArr.push(textArr.shift())
      }
      result.push(tmpArr.join(''));
    }
    return result;
  },
  //生成名片
  createNameCard: function () {
    //
    if (!this.data.userInfo_share.mobile) {
      return;
    }
    wx.showLoading({
      title: '生成名片',
      mask: true
    });
    //先清空画布
    /* this.data.ctx.clearRect(0, 0, app.globalData.windowWidth, app.globalData.windowHeight);
    //
    this.data.ctx.setFillStyle('#fff');
    this.data.ctx.fillRect(0, 0, app.globalData.windowWidth, app.globalData.windowHeight);
    this.data.ctx.draw(); */
    app.globalData.clearCanvas.call(this);
    //绘制名片
    this.paintBg().then(() => {
      return this.paintUserInfo();
    }).then(() => {
      let userName = this.data.employeeInfo.name || '';
      let position = this.data.employeeInfo.position || '';
      return this.paintIntro(userName, position);
    }).then(topY => {
      return this.paintQrCode(topY);
    }).then(() => {
      let timer = null;
      clearTimeout(timer);
      timer = setTimeout(() => {
        //
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          canvasId: 'index-canvas',
          width: app.globalData.windowWidth,
          height: '468',
          //fileType: 'jpg',
          success: res => {
            //console.log(res);
            this.setData({
              canvasImgSrc: res.tempFilePath,
              showCanvasPop: false
            });
          },
          fail: function (res) {
            console.log(res)
          },
          complete: () => {
            wx.hideLoading();
          }
        });
      }, 200);
    }).catch(err => {
      console.log(err);
      wx.showModal({
        title: '提示',
        content: err + '',
        showCancel: false
      });
    });
  },
  //名片保存到本地???
  saveNameCardLocal: function () {
    return app.globalData.saveCanvasImg.call(this,this.data.canvasImgSrc)
  },
  //发送名片给好友
  sendCanvasImgToFriend: function () {
    //
    wx.previewImage({
      urls: [this.data.canvasImgSrc],
      success: res => {},
      fail: err => {}
    });
    //
  },
  //拨打电话
  makePhone: function () {
    //
    if (!this.data.userInfo_share.mobile) {
      return;
    }
    //
    if (this.data.employeeInfo.mobile) {
      wx.makePhoneCall({
        phoneNumber: this.data.employeeInfo.mobile,
        success: res => {},
        fail: err => {}
      })
    } else {
      wx.showToast({
        icon: 'none',
        title: '暂无该员工的手机号码'
      });
    }
  },
  //添加微信
  addWechat: function () {
    //
    if (!this.data.userInfo_share.mobile) {
      return;
    }
    //企业员工
    if (this.data.userInfo_share.state === '1'){
      wx.showToast({
        icon:'none',
        title:'员工不能添加自己'
      });
      return;
    }
    /* this.setData({
      showAddWechatPop: false
    });
    //
    wx.downloadFile({
      url: this.data.employeeInfo.qr_code,
      success: res => {
        wx.previewImage({
          urls: [res.tempFilePath],
        })
      }
    }) */
  },
  //加群领券
  joinGroup:function(){
    if (!this.data.userInfo_share.mobile) {
      return;
    }
    //企业员工
    if (this.data.userInfo_share.state === '1'){
      wx.showToast({
        icon:'none',
        title:'不能邀请自己加入群聊'
      });
      return;
    }
  },
  //隐藏添加微信弹层
  hideAddWechatPop: function () {
    this.setData({
      showAddWechatPop: true
    })
  },
  //发送邮件--复制邮箱
  sendEmail: function (e) {
    //
    if (!this.data.userInfo_share.mobile) {
      return;
    }
    //
    let {
      email
    } = e.currentTarget.dataset;
    if (email) {
      wx.setClipboardData({
        data: email,
        success: function (res) {
          wx.getClipboardData({
            success: res => {
              //console.log(res);
              wx.showToast({
                title: '复制邮箱成功'
              })
            }
          })
        },
        fail: err => {

        }
      })
    } else {
      wx.showToast({
        icon: 'none',
        title: '暂无该员工的邮箱'
      });
    }
  },
  /* 隐藏canvas弹层 */
  hideCanvasPop: function () {
    this.setData({
      showCanvasPop: true
    });
  },
  //主推产品跳转产品页
  goToProPage: function (e) {
    //
    if (!this.data.userInfo_share.mobile) {
      return;
    }
    //console.log(e.currentTarget.dataset)
    let {
      index,
      info
    } = e.currentTarget.dataset;
    //
    app.globalData.fromProductPage = true;
    //
    wx.navigateTo({
      url: '/pages/shoppingMallMini/shoppingMallMini',
      success: res => {
        res.eventChannel.emit('fromProductPage', {
          info: info
        })
      }
    });
  }
});